package org.madmac.controller.maquina;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.madmac.controller.validate.Validate;
import org.madmac.maquina.Maquina;
import org.madmac.maquina.MaquinaBo;
import org.madmac.maquina.MaquinaDao;
import org.madmac.pessoa.Pessoa;
import org.madmac.pessoa.PessoaDao;
import org.madmac.servlet.action.Action;
import org.madmac.servlet.form.Form;
import org.madmac.setor.Setor;
import org.madmac.setor.SetorDao;

/**
 *
 * @author atila camurca
 */
public class MaquinaServlet extends HttpServlet {

   private static final long serialVersionUID = 1L;

   /**
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();
      try {
         /* 
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet MaquinaServlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>Servlet MaquinaServlet at " + request.getContextPath () + "</h1>");
         out.println("</body>");
         out.println("</html>");
          */
      } finally {
         out.close();
      }
   }

   /**
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      try {
         if (request.getParameter("form") != null) {
            if (Form.ADD.equals(Form.valueOf(request.getParameter("form")))) {
               List<Setor> listaSetor = SetorDao.getInstance().findAll();
               int count = listaSetor.size();
               request.setAttribute("setores", listaSetor);
               request.setAttribute("count", count);
               request.setAttribute("form", Form.ADD);
            }
         } else if (request.getParameter("action") != null) {
            if (Action.LIST_ALL.equals(Action.valueOf(request.getParameter("action")))) {
               System.out.println("LIST ALL"); // debug
               Integer idSetor = null;
               if (request.getParameter("id_setor") != null && !request.getParameter("id_setor").isEmpty()) {
                  idSetor = Integer.parseInt(request.getParameter("id_setor"));
               }
               List<Maquina> listMaquina = MaquinaDao.getInstance().findAllByIdSetor(idSetor);
               List<Setor> listaSetor = SetorDao.getInstance().findAll();
               int count = listaSetor.size();
               String currentSetor = null;
               if (listMaquina.size() > 0) {
                  currentSetor = listMaquina.get(0).getSetor().getNome();
               }
               request.setAttribute("maquinas", listMaquina);
               request.setAttribute("setores", listaSetor);
               request.setAttribute("count", count);
               request.setAttribute("current_setor", currentSetor);
               request.setAttribute("action", Action.LIST_ALL);
            }
         }
      } catch (Exception e) {
         System.out.println("Erro: " + e.getMessage());
         //e.printStackTrace();
         request.setAttribute("error", e);
         request.setAttribute("action", Action.ERROR);
      } finally {
         RequestDispatcher dispatcher = request.getRequestDispatcher("maquina/maquina.jsp");
         dispatcher.forward(request, response);
      }
   }

   /**
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      // se o id vir nulo, chama o criar maquina.
      try {
         if (request.getParameter("id") == null) {

            String responsavel = null;
            Pessoa searchPessoa = null;
            // DONE: permitir que a máquina não necessite sempre de um responsável.
            if (request.getParameter("pessoa") != null && !request.getParameter("pessoa").isEmpty()) {
               responsavel = request.getParameter("pessoa").trim();
               try {
                  searchPessoa = PessoaDao.getInstance().selectByNome(responsavel);
               } catch (Exception ex) {
                  request.setAttribute("error", ex);
                  request.setAttribute("action", Action.ERROR);
               }

               if (searchPessoa != null) {
                  // redirecionar com mensagem responsavel nao encontrado.
                  request.setAttribute("error", new Exception("Responsável não encontrado."));
                  request.setAttribute("action", Action.ERROR);
               }
            }

            /**
             * É PRECISO VALIDAR O USUÁRIO ESCOLHIDO PELO AUTOCOMPLETE.
             * E DEVOLVER SOMENTE O 'code_pessoa' FAZENDO UMA BUSCA EM 'madmac.pessoa'.
             */
            // TODO: buscar o id da pessoa em adicionar_maquina.jsp dentro do autocomplete!
            // DONE: permitir que a máquina não necessite sempre de um setor.
            String sistema_op = request.getParameter("sistema_op").trim();
            String modelo = request.getParameter("modelo");
            String filename = request.getParameter("tombamento").trim();

            Maquina maquina = new Maquina();
            maquina.setTombamento(Validate.integerValue(request.getParameter("tombamento")));
            maquina.getSetor().setIdSetor(Validate.integerValue(request.getParameter("setor")));
            maquina.setSistemaOp(sistema_op);
            maquina.setNomeDominio(request.getParameter("dominio"));

            if (searchPessoa == null) {
               maquina.getPessoa().setIdPessoa(null);
            } else {
               maquina.getPessoa().setIdPessoa(searchPessoa.getIdPessoa());
            }

            /* @deprecated referencia-se ao PDF que sera gerado */
            maquina.setFilename(filename);
            maquina.setModelo(modelo);

            try {
               MaquinaBo.getInstance().validateAndCreate(
                       maquina, getServletContext().getRealPath("maduploads/").concat("/"));
               Maquina m = MaquinaDao.getInstance().findByTombamento(maquina.getTombamento());
               request.setAttribute("maquina", m);
               request.setAttribute("action", Action.LIST);
            } catch (Exception e) {
               request.setAttribute("error", e);
               request.setAttribute("action", Action.ERROR);
            }
         } else {
            // editar maquina.
         }
      } catch (Exception e) {
         request.setAttribute("error", e);
         request.setAttribute("action", Action.ERROR);
      } finally {
         RequestDispatcher dispatcher = request.getRequestDispatcher("maquina/maquina.jsp");
         dispatcher.forward(request, response);
      }
   }

   /**
    * Returns a short description of the servlet.
    * @return a String containing servlet description
    */
   @Override
   public String getServletInfo() {
      return "Short description";
   }
}
